package com.qianyu.core.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author wangzhicheng
 * @date 2024/1/22 9:49
 * @description TODO
 */
public class MD5Util {
    public static String md5(String data) {
        try {
            MessageDigest instance = MessageDigest.getInstance("MD5");
            byte[] digest = instance.digest(data.getBytes(StandardCharsets.UTF_8));
            //将处理的字节转16进制
            StringBuffer bf = new StringBuffer();
            for (byte b : digest) {
                bf.append(String.format("%02x", b));
            }
            return bf.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密
     */
    public static String decryptMd5(String md5) {
        MessageDigest instance = null;
        try {
            instance = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = md5.getBytes(StandardCharsets.UTF_8);
        byte[] digested = instance.digest(bytes);

        StringBuilder builder = new StringBuilder();
        for (byte b : digested) {
            builder.append(String.format("%02x", b));
        }
        return builder.toString();

    }


    public static void main(String[] args) {
        System.out.println(md5("123456"));
    }

}
